package com.erp.fin.controller;

import java.util.*;

import com.erp.common.controller.BaseController;
import com.erp.common.utils.*;
import com.erp.fin.domain.ReceiptDO;
import com.erp.fin.domain.ReimburseTypeDO;
import com.erp.fin.service.ReimburseTypeService;
import com.erp.itm.domain.ProjectDO;
import com.erp.itm.service.ProjectService;
import com.erp.oa.domain.NotifyDO;
import com.erp.oa.service.NotifyService;
import com.erp.system.domain.CompanyDO;
import com.erp.system.domain.UserDO;
import com.erp.system.service.CompanyService;
import com.erp.system.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.erp.fin.domain.BillingDO;
import com.erp.fin.service.BillingService;

import javax.servlet.http.HttpServletResponse;

/**
 * 开票管理
 * 
 * @author Eric
 * @email shiliang900713@163.com
 * @date 2019-09-02 10:20:55
 */
 
@Controller
@RequestMapping("/fin/billing")
public class BillingController extends BaseController {
	@Autowired
	private BillingService billingService;

	@Autowired
	private ProjectService projectService;

	@Autowired
	private CompanyService companyService;

	@Autowired
	private ReimburseTypeService reimburseTypeService;

	@Autowired
	private UserService userService;

	@Autowired
	private NotifyService notifyService;


	@GetMapping()
	@RequiresPermissions("fin:billing:billing")
	String Billing(){
	    return "fin/billing/billing";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("fin:billing:billing")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询当前登录人的角色信息是否有部门经理和总经理
		int mgrcount = userService.isManagerOrCeo(getUserId());
		if(mgrcount <=0 ){
			params.put("userIdCreate",getUserId());
		}
		//查询列表数据
        Query query = new Query(params);
		List<BillingDO> billingList = billingService.list(query);
		int total = billingService.count(query);
		PageUtils pageUtils = new PageUtils(billingList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("fin:billing:add")
	String add(){
	    return "fin/billing/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("fin:billing:edit")
	String edit(@PathVariable("id") Long id,Model model){
		BillingDO billing = billingService.get(id);
		model.addAttribute("billing", billing);

		List<ProjectDO> projectDOList = projectService.getNotEndProjectlist();
		model.addAttribute("projectDOList", projectDOList);

		List<CompanyDO> companyDOList = companyService.list(null);
		model.addAttribute("companyDOList", companyDOList);

		List<ReimburseTypeDO> reimburseTypeDOList = reimburseTypeService.list(null);
		model.addAttribute("reimburseTypeDOList", reimburseTypeDOList);
	    return "fin/billing/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("fin:billing:add")
	public R save( BillingDO billing){
		UserDO userDO = ShiroUtils.getUser();
		billing.setStatus(1);
		if(billing.getProjectId() != null){
			ProjectDO projectDO = projectService.get(billing.getProjectId());
			billing.setProjectName(projectDO.getName());
			billing.setProjectNumber(projectDO.getItmNumber());
		}

		if(billing.getBillingComplayId() != null){
			CompanyDO companyDO = companyService.get(billing.getBillingComplayId().intValue());
			billing.setBillingComplayName(companyDO.getName());
		}

		if(billing.getInvoiceTypeid() != null){
			ReimburseTypeDO reimburseTypeDO = reimburseTypeService.get(billing.getInvoiceTypeid());
			billing.setInvoiceType(reimburseTypeDO.getName());
		}
		billing.setUserIdCreate(userDO.getUserId());
		billing.setUserNameCreate(userDO.getName());
		billing.setGmtCreate(new Date());
		if(billingService.save(billing)>0){
			//发通知和邮件通知采购和总经理
			NotifyDO notify = new NotifyDO();
			notify.setType("4");
			notify.setTitle("开票申请");
			notify.setContent(userDO.getName()+"申请项目编号["+billing.getProjectNumber()+"]" +
					"项目名称["+billing.getProjectName()+"]开票,开票金额为："+billing.getInvoiceAmount());
			//查询采购和总经理用户
			List<Long> deprids = new ArrayList<>();
			deprids.add(16L);
			deprids.add(17L);
//			deprids.add(6L);
			List<UserDO> userDOList =userService.getUsersByDeptIds(deprids);
			if(userDOList != null && userDOList.size()>0){
				Long[] userIds = new Long[userDOList.size()];
				for (int i= 0;i<userDOList.size();i++){
					userIds[i] = userDOList.get(i).getUserId();
				}
				notify.setUserIds(userIds);
			}
			notify.setStatus("1");
			notify.setCreateBy(getUserId());
			notifyService.save(notify);
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("fin:billing:edit")
	public R update( BillingDO billing){
		if(billing.getProjectId() != null){
			ProjectDO projectDO = projectService.get(billing.getProjectId());
			billing.setProjectName(projectDO.getName());
			billing.setProjectNumber(projectDO.getItmNumber());
		}

		if(billing.getBillingComplayId() != null){
			CompanyDO companyDO = companyService.get(billing.getBillingComplayId().intValue());
			billing.setBillingComplayName(companyDO.getName());
		}

		if(billing.getInvoiceTypeid() != null){
			ReimburseTypeDO reimburseTypeDO = reimburseTypeService.get(billing.getInvoiceTypeid());
			billing.setInvoiceType(reimburseTypeDO.getName());
		}
		billingService.update(billing);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("fin:billing:remove")
	public R remove( Long id){
		if(billingService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("fin:billing:batchRemove")
	public R remove(@RequestParam("ids[]") Long[] ids){
		billingService.batchRemove(ids);
		return R.ok();
	}


	/**
	 * 审核开票
	 */
	@PostMapping( "/check")
	@ResponseBody
	public R check( Long id){
		if(billingService.checkStatus(id)>0){
			return R.ok();
		}
		return R.error();
	}


	/**
	 * 开票
	 */
	@PostMapping( "/billingcheck")
	@ResponseBody
	public R billingcheck( Long id){
		if(billingService.billingcheck(id)>0){
			//更新收款金额
			BillingDO billingDO = billingService.get(id);
			projectService.updateinvoiceAmount(billingDO.getInvoiceAmount(),billingDO.getProjectId());
			return R.ok();
		}
		return R.error();
	}


	@GetMapping("/getInvoiceByitm/{id}")
	String getInvoiceByitm(@PathVariable("id") Long id,Model model){
		List<BillingDO> billingDOList = billingService.getInvoiceByitm(id);
		model.addAttribute("billingDOList", billingDOList);
		model.addAttribute("itmid", id);
		return "fin/billing/billingByitm";
	}


	@PostMapping("/exportData")
	@ResponseBody
	public void exportData( Long itmid, HttpServletResponse response){
		List<BillingDO> billingDOList = billingService.getInvoiceByitm(itmid);
		ExcelUtil.exportExcel(billingDOList,"开票记录","开票记录",BillingDO.class,"开票记录.xls",response);
	}

	@PostMapping("/exportDataBylist")
	@ResponseBody
	public void exportDataBylist( BillingDO billing, HttpServletResponse response){
		Map<String, Object> params = new HashMap<>();

		if(StringUtils.isNotBlank(billing.getProjectNumber())){
			params.put("projectNumber",billing.getProjectNumber());
		}
		if(StringUtils.isNotBlank(billing.getProjectName())){
			params.put("projectName",billing.getProjectName());
		}
		if(StringUtils.isNotBlank(billing.getBillingComplayName())){
			params.put("billingComplayName",billing.getBillingComplayName());
		}
		if(StringUtils.isNotBlank(billing.getReceiptName())){
			params.put("receiptName",billing.getReceiptName());
		}
		if(billing.getTaxRate() != null){
			params.put("taxRate",billing.getTaxRate());
		}
		if(StringUtils.isNotBlank(billing.getUserNameCreate())){
			params.put("userNameCreate",billing.getUserNameCreate());
		}
		if(billing.getInvoiceTimeend() != null){
			params.put("invoiceTimeend",billing.getInvoiceTimeend());
		}
		if(billing.getInvoiceTimeStr() != null){
			params.put("invoiceTimeStr",billing.getInvoiceTimeStr());
		}
		List<BillingDO> billingDOList = billingService.list(params);
		ExcelUtil.exportExcel(billingDOList,"开票记录","开票记录",BillingDO.class,"开票记录.xls",response);
	}


	@GetMapping("/uploadInfo/{id}")
	String uploadInfo(@PathVariable("id") Long id,Model model){
		BillingDO billingDO = billingService.get(id);
		model.addAttribute("billingDO", billingDO);
		return "fin/billing/uploadinfo";
	}
}
